package exercises.leetcode;

/**
 * <a href="https://leetcode-cn.com/problems/binary-search/">
 * 704. 二分查找</a>
 *
 * @author or2
 * @Description 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
 * @create 2021年09月19日 时间: 14:24
 */
public class No704 {
    public int search(int[] nums, int target) {
        int rightIndex = nums.length;
        if (rightIndex == 1) {
            return target == nums[0] ? 0 : -1;
        }
        int leftIndex = 0;
        int midIndex;

        /*搜索区间 - [leftIndex, rightIndex)*/
        while (leftIndex < rightIndex) {
            midIndex = leftIndex + (rightIndex - leftIndex >> 1);
            int compare = (target < nums[midIndex]) ? -1 : ((target == nums[midIndex]) ? 0 : 1);
            switch (compare) {
                case 0:
                    return midIndex;
                case -1:
                    rightIndex = midIndex;
                    break;
                case 1:
                    leftIndex = midIndex + 1;
            }
        }

        return -1;
    }
}
